
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbYardParamsSets;
using JYJ.AiYard.StationManagement.TbYardParamsSets.Dtos;
using JYJ.AiYard.StationManagement.TbYardParamsSets.DomainService;
using JYJ.AiYard.StationManagement.TbYardParamsSets.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.TbStationParams;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYardParamsSets
{
    /// <summary>
    /// TbYardParamsSet应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardParamsSetAppService : AiYardAppServiceBase, ITbYardParamsSetAppService
    {
        #region 构造函数
        private readonly IRepository<TbYardParamsSet, long> _entityRepository;

        private readonly ITbYardParamsSetManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        protected IHttpContextAccessor _httpContext;

        private readonly IHttpService _httpService;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardParamsSetAppService(
        IRepository<TbYardParamsSet, long> entityRepository
        ,ITbYardParamsSetManager entityManager
           , IHttpService httpService
             , IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
             , IHttpContextAccessor httpContextAccessor
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
            _httpContext = httpContextAccessor;
            _httpService = httpService;
        }
        #endregion

        #region 分页查询
        /// <summary>
        /// 获取TbYardParamsSet的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardParamsSetPermissions.Query)] 
        public async Task<PagedResultDto<TbYardParamsSetDb>> GetPaged(GetTbYardParamsSetsInput input)
		{
            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query = await _aiYardDbTableIssuedCard.QueryTableYardParamsSet(StationList);
            var query1 = query.AsQueryable();

            var count = query1.Count();

            var entityList = query1
                .OrderBy(input.Sorting).AsNoTracking()
                .PageBy(input)
                .ToList();

            return new PagedResultDto<TbYardParamsSetDb>(count, entityList);
        }
        #endregion

        #region 根据ID查询
        /// <summary>
        /// 通过指定id获取TbYardParamsSetListDto信息
        /// </summary>
        [AbpAuthorize(TbYardParamsSetPermissions.Query)] 
		public async Task<TbYardParamsSetListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYardParamsSetListDto>();
		}
        #endregion

        #region 添加修改
        /// <summary>
        /// 获取编辑 TbYardParamsSet
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardParamsSetPermissions.Create,TbYardParamsSetPermissions.Edit)]
		public async Task<GetTbYardParamsSetForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYardParamsSetForEditOutput();
            TbYardParamsSetEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbYardParamsSetEditDto>(); 
			}
			else
			{
				editDto = new TbYardParamsSetEditDto();
			}

			output.TbYardParamsSet = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYardParamsSet的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardParamsSetPermissions.Create,TbYardParamsSetPermissions.Edit)]
		public async Task<Dictionary<string, string>> CreateOrUpdate(CreateOrUpdateTbYardParamsSetInput input)
		{
            if (input.TbYardParamsSet.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbYardParamsSet.Id.HasValue)
			{
				return await Update(input.TbYardParamsSet);
			}
			else
			{
				return await Create(input.TbYardParamsSet);
			}
		}


        /// <summary>
        /// 新增TbYardParamsSet
        /// </summary>
        [AbpAuthorize(TbYardParamsSetPermissions.Create)]
        protected virtual async Task<Dictionary<string, string>> Create(TbYardParamsSetEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            //当为相机时查看是否已经新增
            
            Dictionary<string, string> di = new Dictionary<string, string>();
            int resultValue = 0;
            if (input.tPass_Client_ID <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "客户端不允许为空");
                resultValue = 1;
                return di;
            }
            if (input.tPass_ID <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道编号不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_SNo <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道序号不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Vdi <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "监控主机不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Onwer <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "所属车场不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Pay <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道类型不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Client_ID <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "客户端不允许为空");
                resultValue = 1;
                return di;
            }
            var query1 = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
              && o.tPass_Client_ID == input.tPass_Client_ID  && o.tPass_ID == input.tPass_ID && o.tPass_SNo == input.tPass_SNo).ToList();
            if (query1.Count > 0)
            {
                //同一通道排序相同，不充许添加
                di.Add("retype", "-1");
                di.Add("revalue", "同一通道排序相同");
                resultValue = 1;
                return di;
            }

            //同一岗亭不能同一相机及读卡器
            if (input.tPass_Vdi > 0)
            {
                var query = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
                && o.tPass_Client_ID == input.tPass_Client_ID && o.tPass_Vdi == input.tPass_Vdi).ToList();
                if (query.Count > 0)
                {
                    //相机存在，不充许添加
                    di.Add("retype", "-1");
                    di.Add("revalue", "同一岗亭此相机已经添加");
                    resultValue = 1;
                    return di;
                }
            }
            if (input.tPass_Ldi > 0)
            {
                var query = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
                && o.tPass_Client_ID == input.tPass_Client_ID && o.tPass_Vdi == input.tPass_Ldi).ToList();
                if (query.Count > 0)
                {                    
                    di.Add("retype", "-1");
                    di.Add("revalue", "同一岗亭此读卡器已经添加");
                    resultValue = 1;
                    return di;
                }
            }
            if (resultValue == 0)
            { 
                var entity = input.MapTo<TbYardParamsSet>();


                entity = await _entityRepository.InsertAsync(entity);
                di.Add("retype", "1");
                di.Add("revalue", "添加成功"); 
            }
            return di;
        }

		/// <summary>
		/// 编辑TbYardParamsSet
		/// </summary>
		[AbpAuthorize(TbYardParamsSetPermissions.Edit)]
		protected virtual async Task<Dictionary<string, string>> Update(TbYardParamsSetEditDto input)
		{
            Dictionary<string, string> di = new Dictionary<string, string>();
            int resultValue = 0;
            if (input.tPass_Client_ID <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "客户端不允许为空");
                resultValue = 1;
                return di;
            }
            if (input.tPass_ID <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道编号不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_SNo <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道序号不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Vdi <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "监控主机不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Onwer <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "所属车场不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            if (input.tPass_Pay <= 0)
            {
                di.Add("retype", "-1");
                di.Add("revalue", "通道类型不允许为空或小于等于0");
                resultValue = 1;
                return di;
            }
            var query1 = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
              && o.tPass_Client_ID == input.tPass_Client_ID && o.tPass_ID == input.tPass_ID && o.tPass_SNo == input.tPass_SNo && o.Id != input.Id).ToList();
            if (query1.Count > 0)
            {
                //同一通道排序相同，不充许添加
                di.Add("retype", "-1");
                di.Add("revalue", "同一通道排序相同");
                resultValue = 1;
                return di;
            }           
            //同一岗亭不能同一相机及读卡器
            if (input.tPass_Vdi > 0)
            {
                var query = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
                && o.tPass_Client_ID == input.tPass_Client_ID && o.tPass_Vdi == input.tPass_Vdi && o.Id != input.Id).ToList();
                if (query.Count > 0)
                {
                    //相机存在，不充许添加
                    di.Add("retype", "-1");
                    di.Add("revalue", "同一岗亭此相机已经添加");
                    resultValue = 1;
                    return di;
                }
            }
            if (input.tPass_Ldi > 0)
            {
                var query = _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID
                && o.tPass_Client_ID == input.tPass_Client_ID && o.tPass_Vdi == input.tPass_Ldi && o.Id != input.Id).ToList();
                if (query.Count > 0)
                {
                    di.Add("retype", "-1");
                    di.Add("revalue", "同一岗亭此读卡器已经添加");
                    resultValue = 1;
                    return di;
                }
            }
            if (resultValue == 0)
            {
                var entity = await _entityRepository.GetAsync(input.Id.Value);
                input.MapTo(entity);
                 
                await _entityRepository.UpdateAsync(entity);
                di.Add("retype", "1");
                di.Add("revalue", "修改成功");
            }
            return di;
		}
        #endregion

        #region 删除 
        /// <summary>
        /// 删除TbYardParamsSet信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardParamsSetPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbYardParamsSet的方法
		/// </summary>
		[AbpAuthorize(TbYardParamsSetPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}
        #endregion

        #region 车场参数List
        /// <summary>
        /// 车场参数List
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbYardParamsSetPermissions.ParamsSet)]
        public async Task<List<TbStationParam>> GetTbStationParamsList(long Station_ID)
        {
            
            _aiYardDbTableIssuedCard.InitYardParams(Station_ID, 0);
            return _aiYardDbTableIssuedCard.GetTbStationParamTable(Station_ID);
        }
        [AbpAuthorize(TbYardParamsSetPermissions.ParamsSet)]
        public async Task<List<TbStationParam>> GetTbStationDefaultParamsList(long Station_ID)
        {
            _aiYardDbTableIssuedCard.InitYardParams(Station_ID, -999);
            return _aiYardDbTableIssuedCard.GetTbStationParamTable(Station_ID);
        }
        #endregion

        #region 保存车场参数
        /// <summary>
        /// 保存车场参数
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(TbYardParamsSetPermissions.ParamsSetEdit)]
        public async Task<Dictionary<string, string>> UpdateStationParams(List<TbStationParam> input)
        {
            return _aiYardDbTableIssuedCard.UpdateStationParams(input);            
        }
        #endregion

        #region GetGateUrl获取通道二维码       
        /// <summary>
        ///  GetGateUrl获取通道二维码
        /// </summary>
        /// <param name="StationId">组织ID  Station_ID</param>
        /// <param name="ClientId">电脑ID  tPass_Client_ID</param>
        /// <param name="PassId">通道ID tPass_ID</param>
        /// <param name="PassIndex">tPass_SNo排序序号</param>
        /// <returns></returns>
        public string GetGateUrl(long StationId,long ClientId, int PassId,int PassIndex)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetGateUrl?host=https%3A%2F%2F" + host + "%2F&StationId=" + StationId.ToString().Trim() + "&PassId=" + PassId.ToString().Trim() + "&PassIndex=" + PassIndex.ToString().Trim() + "&ClientId=" + ClientId.ToString().Trim();
            return _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region GetGateUrl获取自行开闸二维码       
        /// <summary>
        ///  GetGateUrl获取通道二维码
        /// </summary>
        /// <param name="StationId">组织ID  Station_ID</param>
        /// <param name="ClientId">电脑ID  tPass_Client_ID</param>
        /// <param name="PassId">通道ID tPass_ID</param>
        /// <param name="PassIndex">tPass_SNo排序序号</param>
        /// <returns></returns>
        public string GetOpenGateUrl(long StationId, long ClientId, int PassId, int PassIndex)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.pypark.cn";
#endif
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetOpenGateUrl?host=https%3A%2F%2F" + host + "%2F&StationId=" + StationId.ToString().Trim() + "&PassId=" + PassId.ToString().Trim() + "&PassIndex=" + PassIndex.ToString().Trim() + "&ClientId=" + ClientId.ToString().Trim();
            return _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region GetGateUrl获取通道小程序码       
        /// <summary>
        ///  GetGateUrl获取通道小程序码
        /// </summary>
        /// <param name="StationId">组织ID  Station_ID</param>
        /// <param name="ClientId">电脑ID  tPass_Client_ID</param>
        /// <param name="PassId">通道ID tPass_ID</param>
        /// <param name="PassIndex">tPass_SNo排序序号</param>
        /// <returns></returns>
        public string GetGateUrl_Mini(long StationId, long ClientId, int PassId, int PassIndex, int width, string env_version, string color, bool is_hyaline)
        {
            bool check_path = false;
            if (env_version == "release") { check_path = true; }
            bool auto_color = false;
            string miniParams = "&check_path=" + check_path.ToString() + "&env_version=" + env_version + "&width=" + width + "&auto_color=" + auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString();

            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetGateUrl_Mini?host=pages/index/index&StationId=" + StationId.ToString().Trim() + "&PassId=" + PassId.ToString().Trim() + "&PassIndex=" + PassIndex.ToString().Trim() + "&ClientId=" + ClientId.ToString().Trim()+ miniParams;
            string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
            if (fileName.StartsWith("!"))
            {
                return fileName;
            }
            return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
        }
        #endregion

        #region GetGatePayUrl获取通道支付二维码
        /// <summary>
        ///  GetGatePayUrl获取通道支付二维码
        /// </summary>
        /// <param name="StationId">组织ID  Station_ID</param>
        /// <param name="ClientId">电脑ID  tPass_Client_ID</param>
        /// <param name="PassId">通道ID tPass_ID</param>       
        /// <returns></returns>    
        public string GetGatePayUrl(long StationId, long ClientId, int PassId)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetGatePayUrl?host=https%3A%2F%2F" + host + "%2F&StationId=" + StationId.ToString().Trim() + "&PassId=" + PassId.ToString().Trim() + "&ClientId=" + ClientId.ToString().Trim();
            return  _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region GetGatePayUrl获取通道支付小程序码
        /// <summary>
        ///  GetGatePayUrl获取通道支付小程序码
        /// </summary>
        /// <param name="StationId">组织ID  Station_ID</param>
        /// <param name="ClientId">电脑ID  tPass_Client_ID</param>
        /// <param name="PassId">通道ID tPass_ID</param>       
        /// <returns></returns>    
        public string GetGatePayUrl_Mini(long StationId, long ClientId, int PassId, int width, string env_version, string color, bool is_hyaline)
        {
            bool check_path = false;
            if (env_version == "release") { check_path = true; }
            bool auto_color = false;
            string miniParams = "&check_path=" + check_path.ToString() + "&env_version=" + env_version + "&width=" + width + "&auto_color=" + auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString();

            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetGatePayUrl_Mini?host=pages/index/index&StationId=" + StationId.ToString().Trim() + "&PassId=" + PassId.ToString().Trim() + "&ClientId=" + ClientId.ToString().Trim()+ miniParams;
            string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
            if (fileName.StartsWith("!"))
            {
                return fileName;
            }
            return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
        }
        #endregion

        #region GetStationUrl获取场所支付二维码
        public string GetStationUrl(long Station_Id)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif 
            long TenantId = AbpSession.TenantId == null ? 0 : (long)AbpSession.TenantId;
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetStationUrl?host=https%3A%2F%2F" + host + "%2F&StationId=" + Station_Id.ToString().Trim() + "&TenantId=" + TenantId.ToString().Trim() ;
            return _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region GetStationUrl获取场所支付小程序码
        public string GetStationUrl_Mini(long Station_Id, int width, string env_version, string color, bool is_hyaline)
        {
            bool check_path = false;
            if (env_version == "release") { check_path = true; }
            bool auto_color = false;
            string miniParams = "&check_path=" + check_path.ToString() + "&env_version=" + env_version + "&width=" + width + "&auto_color=" + auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString();

            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif 
            long TenantId = AbpSession.TenantId == null ? 0 : (long)AbpSession.TenantId;
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetStationUrl_Mini?host=pages/index/index&StationId=" + Station_Id.ToString().Trim() + "&TenantId=" + TenantId.ToString().Trim() + miniParams;
            string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
            if (fileName.StartsWith("!"))
            {
                return fileName;
            }
            return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
        }
        #endregion
        /// <summary>
        /// 导出TbYardParamsSet为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}

    }
}


